package cn.itcast.web;


import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.service.impl.UserServiceImpl;
import cn.itcast.util.OutputStringController;
import cn.itcast.util.ResponseEntity;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import cn.itcast.mapper.userMapper;
import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping(value="/wxshop/user",produces="application/json;charset=UTF-8")
public class UserController {

    @Resource
    UserServiceImpl userService;
    @Resource
    OutputStringController osc;
    @Resource
    userMapper userMapper;

    @Resource
    private cn.itcast.mapper.orderMapper orderMapper;

    @Resource
    private cn.itcast.mapper.gzhMapper gzhMapper;


    @Resource
    private accountMapper accountMapper;

    @Resource
    private withdrawMapper withdrawMapper;

    /**
     * 功能描述: <br>
     * 〈获取用户端的 accessToken〉
     * @Author: lyy
     * @Date: 2020/9/12 11:45
     * @Param: []
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "accessTokenUser")
    public ResponseEntity accessTokenUser(){
        gzhExample example = new gzhExample();
        gzhExample.Criteria criteria = example.createCriteria();
        criteria.andOpenAppidEqualTo("用户端");
        List<gzh> gzhList = gzhMapper.selectByExample(example);
        if(!gzhList.isEmpty() || gzhList.size()>0){
            return new ResponseEntity(200,"高总要的数据啊！！！",gzhList.get(0));
        }else return new ResponseEntity().error_300();

    }

    /**
     *
     * @Description:
     * 修改用户数据
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody Map<String,String> map){
        log.debug("修改用户数据");
        user user = new user();

        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("openId")))){
            user.setOpenId(map.get("openId"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("nickName")))){
            user.setNickName(map.get("nickName"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(Byte.valueOf(map.get("gender"))))){
            user.setGender(Byte.valueOf(map.get("gender")));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("phone")))){
            user.setUserPhone(map.get("phone"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userID")))){
            user.setUserIdNumber(map.get("userID"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userName")))){
            user.setUserName(map.get("userName"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("exploitName")))){
            user.setExploitName(map.get("exploitName"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("exploitOpenId")))){
            user.setExploitOpenId(map.get("exploitOpenId"));
        }

        //返回结果
        String results = "";
        boolean isdelect = userService.updateUserInfo(user);
        if(isdelect){
            results = osc.success("yes");
            log.debug("修改用户数据成功");
        }else{
            results = osc.failure("no");
            log.debug("修改用户数据失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查找用户数据
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUserInfo")
    public String findUserInfo(@RequestBody Map<String,String> map){
        log.debug("查找用户数据");
        String openId = map.get("openId");

        //返回结果
        String results = "";
        user user = userService.findUserInfo(openId);
        if(user!=null){
            results = osc.resultSuccess("yes",user);
            log.debug("查找用户数据成功");
        }else{
            results = osc.failure("no");
            log.debug("查找用户数据失败");
        }

        return results;
    }


    /**
     *
     * @Description:
     * 查询用户下单次数
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findCountOrder")
    public String findCountOrder(@RequestBody Map<String,String> map){
        log.debug("查询用户下单次数");
        String openId = map.get("openId");

        //返回结果
        String results = "";
        int count = userService.findCountOrder(openId);
        if(count!=0){
            results = osc.resultSuccess("yes",count);
            log.debug("查询用户下单次数成功");
        }else{
            results = osc.failure("no");
            log.debug("查询用户下单次数失败");
        }

        return results;
    }


    /**
     *
     * @Description:
     * 查询用户累计收益
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findCountEarning")
    public String findCountEarning(@RequestBody Map<String,String> map){
        log.debug("查询用户累计收益");
        String openId = map.get("openId");

        //返回结果
        String results = "";
        double count = userService.findCountEarning(openId);
        if(count!=0){
            results = osc.resultSuccess("yes",count);
            log.debug("查询用户累计收益成功");
        }else{
            results = osc.failure("no");
            log.debug("查询用户累计收益失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 增加用户一级二级分销
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/addDistribution")
    public String addDistribution(@RequestBody Map<String,String> map){
        log.debug("增加用户一级二级分销");
        String openId = map.get("openId");
        String distribution = map.get("distribution");

        //返回结果
        String results = "";
        boolean isadd = userService.addDistribution(openId,distribution);
        if(isadd){
            results = osc.resultSuccess("yes","");
            log.debug("增加用户一级二级分销成功");
        }else{
            results = osc.failure("no");
            log.debug("增加用户一级二级分销失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查看用户所有收益
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findAllEarnings")
    public String findAllEarnings(@RequestBody Map<String,String> map){
        log.debug("查看用户所有收益");
        String openId = map.get("openId");

        //返回结果
        String results = "";
        List<earnings> earnings = userService.findAllEarnings(openId);
        if(!earnings.isEmpty()){
            results = osc.resultSuccess("yes",earnings);
            log.debug("查看用户所有收益成功");
        }else{
            results = osc.failure("no");
            log.debug("查看用户所有收益失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查看用户分类收益
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findTypeEarnings")
    public String findTypeEarnings(@RequestBody Map<String,String> map){
        log.debug("查看用户分类收益");
        String openId = map.get("openId");

        //返回结果
        String results = "";
        Map<String,List<earnings>> earnings = userService.findTypeEarnings(openId);
        if(!earnings.isEmpty()){
            results = osc.resultSuccess("yes",earnings);
            log.debug("查看用户分类收益成功");
        }else{
            results = osc.failure("no");
            log.debug("查看用户分类收益失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查询用户分享二维码
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUserEwm")
    public String findUserEwm(@RequestBody Map<String,String> map) throws IOException {
        log.debug("查询用户分享二维码");
        //返回结果
        String results = "";
        String openId = map.get("openId");
        String url = userService.findUserToken(openId);
        url = succussUrl(url,openId);   //判断用户推广二维码地址是否能访问,不能则删除
        if(!url.equals("")){
            results = osc.resultSuccess("yes",url);
            log.debug("查询用户分享二维码成功");
        }else{
            results = osc.failure("no");
            log.debug("查询用户分享二维码失败");
        }
        return results;
    }

    /**
     *
     * @Description: 判断用户推广二维码地址是否能访问,不能则删除
     *
     * @auther: 张松
     * @date: 9:30 2020/8/8
     * @param: [url, openId]
     * @return: java.lang.String
     *
     */

    public String succussUrl(String url,String openId){
        int responseCode=0 ;
        try {
            URL u = new URL(url);
            HttpURLConnection huc = (HttpURLConnection) u.openConnection();
            huc.setRequestMethod("HEAD");
            huc.setConnectTimeout(5000); //视情况设置超时时间
            huc.connect();
            responseCode = huc.getResponseCode();
            if (responseCode==HttpURLConnection.HTTP_OK){
                return url;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.deleteUserNative(openId);//清除用户二维码地址
        return "";
    }




    /**
     *
     * @Description:
     * 查看用户分销伙伴
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUserDistribution")
    public String findUserDistribution(@RequestBody Map<String,String> map){
        log.debug("查看用户分销伙伴");

        String openId = map.get("openId");
        //返回结果
        String results = "";
        Map<String,List<user>> usersMap = userService.findUserDistribution(openId);

        if(!usersMap.isEmpty()){
            results = osc.resultSuccess("yes",usersMap);
            log.debug("查看用户分销伙伴成功");
        }else{
            results = osc.failure("no");
            log.debug("查看用户分销伙伴失败");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 派单
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/sendOrder")
    public String sendOrder(@RequestBody Map<String,String> map){
        log.debug("派单开始");
        //返回结果
        String results ="";
        //获取页数
        Integer orderId = Integer.parseInt(map.get("orderId"));
        String openId = map.get("horesmanOpenId");
        String name = map.get("horesmanName");
        String DispatchOpenId = map.get("openId");



        boolean issend = userService.sendOrder(orderId,openId,name,DispatchOpenId);
        if(!issend){
            results = osc.failure("no");
            log.debug("派单失败");
        }else {
            results = osc.success("yes");
            log.debug("派单成功");
        }

        return results;
    }


    /**
     *
     * @Description:
     * 查询待审核的提现记录
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUnWithdraw")
    public String findUnWithdraw(@RequestBody Map<String,String> map){
        log.debug("查询待审核的提现记录开始");
        //返回结果
        String results ="";



        List<withdraw> withdraws = userService.findUnWithdraw();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for(int i = 0 ;i<withdraws.size() ;i++){
            if(StringUtils.isNotBlank(ObjectUtils.toString(withdraws.get(i).getApplyTime()))){
                withdraws.get(i).setApplyTime_string(sdf.format(withdraws.get(i).getApplyTime()));
            }
        }
        if(withdraws.isEmpty()){
            results = osc.failure("no");
            log.debug("查询待审核的提现记录失败");
        }else {
            results = osc.resultSuccess("yes",withdraws);
            log.debug("查询待审核的提现记录成功");
        }

        return results;
    }

    @ResponseBody
    @RequestMapping("/sendCheck")
    public String sendCheck(@RequestBody Map<String,Object> map){
        String results= "";
        //获取前台提交的数据
        Integer id = (Integer) map.get("id");
        Boolean aBoolean = userService.checkWithdraw(id);
        if(!aBoolean) {
            results = osc.failure("系统异常，审核通过失败");
        }else {
            results = osc.success("审核成功，该提现申请已通过");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/lostEffect")
    public String lostEffect(@RequestBody Map<String,Object> map){
        String results= "";
        //获取前台提交的数据
        Integer id = (Integer) map.get("id");
        Boolean aBoolean = userService.lostEffect(id);
        if(!aBoolean) {
            results = osc.failure("系统异常，审核失效失败");
        }else {
            results = osc.success("审核失效成功，该提现申请已失效");
        }
        return results;
    }

    @RequestMapping("/getOrder")
    public String getOrder(@RequestBody Map<String,Object> map ){
        String results= "";
        //获取前台提交的数据
        Integer page = (Integer)map.get("page");
        Integer limit = (Integer)map.get("limit");
        String  openId = (String) map.get("openId");
        String state = (String)map.get("orderState");
        Map<String, Object> resultMap = userService.getOrderById(page, limit, openId,state );


        //获取该用户所有的订单记录
        List<order> orderList = (List<order>) resultMap.get("orderList");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for (cn.itcast.pojo.order order : orderList) {
            if (StringUtils.isNotBlank(ObjectUtils.toString(order.getOrderTime()))) {
                order.setOrderTimeString(sdf.format(order.getOrderTime()));
            }
        }

        //获取符合查询条件的总记录条数
        int count = (int)resultMap.get("count");

        if(orderList.isEmpty()){
            results = osc.failure("该用户还没有下过单");
        }
        else {
            results = osc.resultSuccess("yes",orderList, count);
        }
        return results;
    }

    /**
     *
     * @Description:
     * 查询所有帮助中心
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findAllHelp")
    public String findAllHelp(@RequestBody Map<String,String> map){
        log.debug("查询所有帮助中心开始");
        //返回结果
        String results ="";
        List<helpCenter> helps = userService.findAllHelp();
        if(helps.isEmpty()){
            results = osc.failure("no");
            log.debug("查询所有帮助中心失败");
        }else {
            results = osc.resultSuccess("yes",helps);
            log.debug("查询所有帮助中心成功");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查询帮助中心
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findHelp")
    public String findHelp(@RequestBody Map<String,String> map){
        log.debug("查询帮助中心开始");
        Integer id = Integer.parseInt(map.get("id"));
        //返回结果
        String results ="";
        helpCenter help = userService.findHelp(id);
        if(help==null){
            results = osc.failure("no");
            log.debug("查询帮助中心失败");
        }else {
            results = osc.resultSuccess("yes",help);
            log.debug("查询帮助中心成功");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 查询帮助中心
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/isPhone")
    public String isPhone(@RequestBody Map<String,String> map){
        log.debug("查询帮助中心开始");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        boolean isTel = userService.isPhone(openId);
        if(!isTel){
            results = osc.failure("no");
            log.debug("查询帮助中心失败");
        }else {
            results = osc.success("yes");
            log.debug("查询帮助中心成功");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 获取用户手机号
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/findUserPhone")
    public String findUserPhone(@RequestBody Map<String,String> map){
        log.debug("获取用户手机号");
        String encryptedData = map.get("encryptedData");
        String iv = map.get("iv");
        String openId = map.get("openId");
        //返回结果
        String results ="";
        String phone = userService.findUserPhone(encryptedData,iv,openId);
        if(phone.equals("")){
            results = osc.failure("no");
            log.debug("获取用户手机号失败");
        }else {
            results = osc.resultSuccess("yes",phone);
            log.debug("获取用户手机号成功");
        }

        return results;
    }


    /**
     * 功能描述: <br>
     * 〈查看派单人员〉
     * @Author: lyy
     * @Date: 2020/8/19 18:33
     * @Param: [map]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "/PreviousHorseman")
    public ResponseEntity findPreviousHorseman(@RequestBody Map<String,String> map){
        orderExample orderExample = new orderExample();
        orderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(Integer.valueOf(map.get("orderId")));
        List<order> order = orderMapper.selectByExample(orderExample);
        if(order.size()!=0 && order.get(0).getDispatchOpenId()!=null){
            userExample userExample = new userExample();
            userExample.Criteria userCrt = userExample.createCriteria();
            userCrt.andOpenIdEqualTo(order.get(0).getDispatchOpenId());
            List<user> userList = userMapper.selectByExample(userExample);
            return new ResponseEntity(userList);
        }else{
            return new ResponseEntity().error_300();
        }
    }

    /**
     * 功能描述: <br>
     * 〈根据用户openid查询用户资料〉
     * @Author: lyy
     * @Date: 2020/9/8 16:04
     * @Param: [map]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "/findUserAllInfo")
    public ResponseEntity findUserAllInfo(@RequestBody Map<String,String> map){

        if(map.isEmpty()){return new ResponseEntity(401,"参数不能为空！！！");}

        userExample userExample = new userExample();
        userExample.Criteria criteria = userExample.createCriteria();
        criteria.andOpenIdEqualTo(map.get("openId"));
        List<user> userList = userMapper.selectByExample(userExample);

        if(userList.size() != 0){
            return new ResponseEntity(200,"查询成功",userList);
        }else{
            return new ResponseEntity(403,"查询失败" ,userList);
        }
    }



    /**
     * 功能描述: <br>
     * 〈审核提现信息〉
     * @Author: lyy
     * @Date: 2020/10/18 12:36
     * @Param: [map]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "/userWithdrawal")
    public ResponseEntity userWithdrawal(){

        List<withdraw> withdraws = userService.findUnWithdraw();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for(int i = 0 ;i<withdraws.size() ;i++){

            if(StringUtils.isNotBlank(ObjectUtils.toString(withdraws.get(i).getApplyTime()))){
                withdraws.get(i).setApplyTime_string(sdf.format(withdraws.get(i).getApplyTime()));
            }

            accountExample example = new accountExample();
            accountExample.Criteria criteria = example.createCriteria();
            criteria.andOpenIdEqualTo(withdraws.get(i).getOpenId());
            List<account> accountList = accountMapper.selectByExample(example);

            if(accountList.size()>0)
                withdraws.get(i).setAccount_money_balance(accountList.get(0).getAccountMoneyBalance());
                withdraws.get(i).setAccount_money_rental(accountList.get(0).getAccountMoneyRental());
                withdraws.get(i).setAccount_earnings_one_distribution(accountList.get(0).getAccountEarningsOneDistribution());
                withdraws.get(i).setAccount_earnings_two_distribution(accountList.get(0).getAccountEarningsTwoDistribution());

            Double money = withdrawMapper.MoneySum(withdraws.get(i).getOpenId());
            if (money==null){
                money=0.0;
            }
            withdraws.get(i).setSum_money(money);

            userExample userExample = new userExample();
            userExample.Criteria userExampleCriteria = userExample.createCriteria();
            userExampleCriteria.andOpenIdEqualTo(withdraws.get(i).getOpenId());
            List<user> userList = userMapper.selectByExample(userExample);

            if(userList.size()>0){
                if(userList.get(0).getUserName()!=null){
                    withdraws.get(i).setUser_name(userList.get(0).getUserName());
                }else{
                    withdraws.get(i).setUser_name(userList.get(0).getNickName());
                }
            }

            if(withdraws.get(i).getUserType().equals("1")){
                withdraws.get(i).setType_name("用户");
            }else if(withdraws.get(i).getUserType().equals("0")){
                withdraws.get(i).setType_name("骑手");
            }else if(withdraws.get(i).getUserType().equals("2")){
                withdraws.get(i).setType_name("商户");
            }

        }

        if(withdraws.size()>0){
            return new ResponseEntity(200,"查询成功",withdraws);
        }else{
            return new ResponseEntity(403,"查询失败");
        }
    }






}
